﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System;

namespace Xceed.Silverlight.DataGrid
{
  public class ColumnCollection : ObservableCollection<Column>
  {
    internal ColumnCollection()
    {
    }

    public virtual Column this[ string fieldName ]
    {
      get
      {
        foreach( Column column in this )
        {
          if( column.FieldName == fieldName )
          {
            return column;
          }
        }
        return null;
      }
    }

    protected override void InsertItem( int index, Column item )
    {
      if( ( Xceed.Utils.Licensing.DesignerProperties.GetIsInDesignMode()
        && ( !item.IsAutoGenerated ) ) )
      {
        Column existingFieldName = this[ item.FieldName ];
        if( existingFieldName != null && existingFieldName.IsAutoGenerated )
        {
          int removedColumnIndex = this.IndexOf( existingFieldName );
          this.RemoveAt( removedColumnIndex );

          if( removedColumnIndex <= index )
            index--;
        }
      }

      if( this[ item.FieldName ] != null )
        throw new InvalidOperationException( string.Format( "A column with fieldName {0} already exists in collection.", item.FieldName ) );


      this.Items.Insert( index, item );
      this.OnPropertyChanged( new PropertyChangedEventArgs( "Count" ) );
      this.OnPropertyChanged( new PropertyChangedEventArgs( "Item[]" ) );
      this.OnCollectionChanged( new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, item, index ) );
    }
  }
}
